package com.zhx.common.user.controller;

import com.zhx.common.user.service.WXMsgService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.common.util.report.qual.ReportUnqualified;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;

/**
 * Description: 微信api交互接口
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("wx/portal/public")
public class WxPortalController {

    @Resource
    private WXMsgService wxMsgService;

    private final WxMpService wxService;
    private final WxMpMessageRouter messageRouter;

    @GetMapping("/test")
    public String getQrCode(@RequestParam Integer code) throws WxErrorException {
        WxMpQrCodeTicket wxMpQrCodeTicket = wxService.getQrcodeService().qrCodeCreateTmpTicket(code, 1000);
        String url = wxMpQrCodeTicket.getUrl();
        System.out.println(url);
        return url;
    }

    //produces属性指定了HTTP响应的内容类型（Content-Type）。

    /**
     * 微信服务器在首次与开发者服务器建立连接时会发送一个验证请求，以确保服务器是可信任的。
     * 这个方法接收并验证微信服务器发送的认证消息，以下是这四个参数的解释：
     * @param signature 微信服务器发送的签名。这是一个由微信服务器根据请求中的timestamp（时间戳）、nonce（随机数）和开发者设置的token（令牌）计算得到的签名值。开发者服务器需要验证这个签名是否正确，以确认请求确实来自微信服务器。
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echostr 这是一个由微信服务器提供的随机字符串，开发者服务器需要返回这个字符串作为验证结果。如果开发者服务器能够正确返回echostr，则微信服务器确认连接建立成功。
     * @return
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {

        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature,
                timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        //验证消息的确来自微信服务器.
        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }

        return "非法请求";
    }

    /**
     *
     * @param code 这个参数是微信在用户授权后提供的授权码。
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/callBack")
    public RedirectView callBack(@RequestParam String code) throws WxErrorException {
        //用户点击登录(扫码成功进入公众号)回调此函数，返回授权码code，根据code获得accessToken
        WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
        //获取用户信息
        WxOAuth2UserInfo userInfo = wxService.getOAuth2Service().getUserInfo(accessToken, "zh_CN");
        //用户授权
        wxMsgService.authorize(userInfo);

        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("www.mallchat.cn");
        return redirectView;
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        log.info("\n接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);

        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
        }

        log.debug("\n组装回复信息：{}", out);
        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }

        return null;
    }
}
